package com.omn.listazakupow.controller;

import java.util.HashMap;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;

import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.theme.ThemeDisplay;
import com.omn.listazakupow.db.model.GrupyTowarow;
import com.omn.listazakupow.db.model.impl.GrupyTowarowImpl;
import com.omn.listazakupow.db.service.GrupyTowarowLocalServiceUtil;

@Controller
@RequestMapping("VIEW")
public class AddGrupyTowarowController {

	@RequestMapping("view")
	public void handleActionRequest(ActionRequest request,
			ActionResponse response) throws Exception {

		int id = -1;
		GrupyTowarow grupyTowarowRob = new GrupyTowarowImpl();
		if (request.getParameter("id") != null) {
			id = Integer.parseInt(request.getParameter("id"));
		}

		response.setRenderParameter("action", "viewGrupyTowarow");

		if (request.getParameter("delete") != null) {
			grupyTowarowRob.setId(id);
			GrupyTowarowLocalServiceUtil.deleteGrupyTowarow(grupyTowarowRob);
			return;
		}
		ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
		User user = themeDisplay.getUser();
		if(user!=null){
			grupyTowarowRob.setUserId(user.getUserId());
		}
		

		if (id == -1)
			grupyTowarowRob.setId(CounterLocalServiceUtil.increment(GrupyTowarow.class.getName()));
		else
			grupyTowarowRob.setId(id);

		String param = request.getParameter("kolejnosc");
		if (param == null || param.trim().isEmpty()) {
			grupyTowarowRob.setKolejnosc(-2);
		} else {
			try {
				grupyTowarowRob.setKolejnosc(Integer.parseInt(param));
			} catch (Exception e) {
				grupyTowarowRob.setKolejnosc(-2);
			}
		}

		param = request.getParameter("opis");
		if (param == null || param.trim().isEmpty()) {
			grupyTowarowRob.setOpis("--Brak opisu--");
		} else {
			grupyTowarowRob.setOpis(param);
		}

		if (id == -1)
			GrupyTowarowLocalServiceUtil.addGrupyTowarow(grupyTowarowRob);
		else
			GrupyTowarowLocalServiceUtil.updateGrupyTowarow(grupyTowarowRob);
	}

	@RequestMapping("view")
	public ModelAndView handleRenderRequest(RenderRequest request,
			RenderResponse response) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();

		return new ModelAndView("addGrupyTowarow", model);
	}

	@RequestMapping
	protected String defaultView() {
		return "view";
	}

}